package com.supermarket.manage.business.cloud.controller;

import com.supermarket.manage.business.cloud.dto.CodeParams;
import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.pojo.MyUser;
import com.supermarket.manage.provider.api.message.CodeService;
import com.supermarket.manage.provider.api.ucenter.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-03 17:20
 **/
@RestController
@RequestMapping("/code")
@Api(value = "CodeSendController", tags = "短信验证码发送接口")
public class CodeSendController {

    @Reference(version = "1.0.0", timeout = 5000)
    private CodeService codeService;

    @Reference(version = "1.0.0")
    private UserService userService;

    /**
     * 用户注册 模板id
     */
    public static final String REGISTER_CODE_MODEL = "SMS_185720087";

    /**
     * 用户绑定手机 模板id
     */
    public static final String BIND_MODEL = "SMS_185810880";


    @PostMapping("/phoneCode")
    @ApiOperation(value = "发送手机验证码", notes = "发送手机验证码")
    public ResponseResult<Void> phoneCode(@Validated @RequestBody CodeParams params) {
        String modelId = params.getModelId();
        //非注册、绑定请求，校验号码是否已注册本系统
        if (!modelId.equals(REGISTER_CODE_MODEL) && !modelId.equals(BIND_MODEL)) {
            MyUser myUser = userService.getUserByUsernameWithNoPermission(params.getPhoneNumber());
            //非用户注册，校验手机号是否为系统用户
            if (null == myUser) {
                return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "该手机号未注册本系统");
            }
        }
        //注册请求校验手机号是否被使用
        else if (modelId.equals(REGISTER_CODE_MODEL)) {
            MyUser myUser = userService.getUserByUsernameWithNoPermission(params.getPhoneNumber());
            //用户注册，校验手机号是否被注册过
            if (myUser != null) {
                return new ResponseResult<>(CodeStatus.ILLEGAL_REQUEST, "该手机号已注册本系统");
            }
        }

        Boolean aBoolean = codeService.sendCodeByPhoneNumber(params.getPhoneNumber(), modelId);
        if (aBoolean) {
            return new ResponseResult<>(CodeStatus.OK, "发送成功,验证码 5分钟 内有效");
        }
        return new ResponseResult<>(CodeStatus.FAIL, "发送失败");
    }
}
